#include <curl/curl.h>
#include "HMAC_SHA1.h"
#include "QGameNetwork.h"
#include "OpenApiConst.h"

QGameNetwork::QGameNetwork()
{
	method = c_strHttpMethod[HTTPMETHOD_GET];
	protocol = c_strHttpProtocol[HTTPPROTOCOL_HTTP];
	curl_global_init( CURL_GLOBAL_ALL );

}

QGameNetwork::~QGameNetwork()
{
	curl_global_cleanup();
}
void QGameNetwork::setmethod(string method)
{
	this->method = method ;
}

void QGameNetwork::setprotocol(string protocol)
{
	this->protocol = protocol ;
}
/*
url :http://119.147.19.43/v3/user/get_info
querystring: 
*/

int QGameNetwork::makeRequestUrl(string url, write_datafunc func, char* userdata)
{
	int ret = 0 ;

	CURL* curl;
	curl = curl_easy_init();
	CURLcode curlcode;

	if ( !curl )
	{
		return -1;
	}


	string urlstr = url ;
	curl_easy_setopt( curl, CURLOPT_URL, urlstr.c_str() );
	

	curl_easy_setopt( curl, CURLOPT_CONNECTTIMEOUT, 10);

	if ( NULL != func )
	{
		curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, func );
		curl_easy_setopt( curl, CURLOPT_WRITEDATA, userdata);
	}
	curl_easy_setopt( curl, CURLOPT_NOSIGNAL, 1L);
	ret = curl_easy_perform( curl );
	curl_easy_cleanup( curl );
	return ret;

}
int QGameNetwork::makeRequest(string url, string querystring,write_datafunc func, char* userdata)
{
	int ret = 0 ;
	
	CURL* curl;
	curl = curl_easy_init();
	CURLcode curlcode;
	
	if ( !curl )
	{
		return -1;
	}

	if ( c_strHttpMethod[HTTPMETHOD_GET] == method )
	{
		string urlstr = url + "?" + querystring;
		curl_easy_setopt( curl, CURLOPT_URL, urlstr.c_str() );
	}
	else
	{
		curl_easy_setopt( curl, CURLOPT_URL, url.c_str() );
		curl_easy_setopt( curl, CURLOPT_POST, 1);
		curl_easy_setopt( curl, CURLOPT_POSTFIELDS, querystring.c_str() );
		curl_easy_setopt( curl, CURLOPT_HEADER, 0 );//100-continue ,set to 0 ,transfer header and body separately
		curl_slist *http_headers = NULL;
		http_headers = curl_slist_append( http_headers, "Expect:");
		curl_easy_setopt( curl, CURLOPT_HTTPHEADER, http_headers);
	}
	
	curl_easy_setopt( curl, CURLOPT_CONNECTTIMEOUT, 10);

	if ( c_strHttpProtocol[HTTPPROTOCOL_HTTPS] == protocol )
	{
		curl_easy_setopt( curl, CURLOPT_SSL_VERIFYPEER, false );
		curl_easy_setopt( curl, CURLOPT_SSL_VERIFYHOST, false );
	}
	if ( NULL != func )
	{
		curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, func );
		curl_easy_setopt( curl, CURLOPT_WRITEDATA, userdata);
	}
	curl_easy_setopt( curl, CURLOPT_NOSIGNAL, 1L);
	ret = curl_easy_perform( curl );
	curl_easy_cleanup( curl );
	
	return ret;
}

